<template>
    <div class="physical-field-select">
        <div class="flex-1 flex-v-center flex-wrap">
            <el-tag v-for="field in displayFields" :key="field.id" class="ms-1" type="info">
                {{ field.name }}
            </el-tag>
        </div>
        <tnxel-button class="px-2"
            :type="updateButtonType"
            text
            bg
            icon="MoreFilled"
            @click="toUpdate"
        />
        <tnxel-dialog v-model="dialog.visible"
            :buttons="dialog.buttons"
            :title="title"
            :width="450"
        >
            <tnxel-alert>选取顺序决定索引字段顺序</tnxel-alert>
            <tnxel-select v-model="model" :items="fields" value-name="id" text-name="name" selector="checkbox"/>
        </tnxel-dialog>
    </div>
</template>

<script>
import tnx from '@/tnx.js';

export default {
    name: 'PhysicalFieldSelect',
    props: {
        modelValue: {
            type: Array, // 字段id数组
            default: () => [],
        },
        fields: Array,
        updateButtonType: String,
        title: {
            type: String,
            default: '选择数据库字段',
        },
    },
    data() {
        return {
            model: this.modelValue,
            dialog: {
                visible: false,
                buttons: tnx.getDefaultDialogButtons('confirm', this.toSubmitUpdate),
            },
        };
    },
    computed: {
        displayFields() {
            let displayFields = [];
            for (let fieldId of this.modelValue) {
                let field = this.fields.find(field => field.id === fieldId);
                if (field) {
                    displayFields.push(field);
                }
            }
            return displayFields;
        },
    },
    watch: {
        modelValue() {
            this.model = this.modelValue;
        },
    },
    methods: {
        toUpdate() {
            this.dialog.visible = true;
        },
        toSubmitUpdate(yes) {
            if (yes) {
                this.$emit('update:modelValue', this.model);
            }
        },
    }
}
</script>

<style lang="scss">
.physical-field-select {
    width: 100%;
    display: flex;
    align-items: center;

    .el-button {
        border-width: 1px;
    }
}
</style>
